package com.vipbbo.spring.transaction;

import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.sql.DataSource;

public class MyTransaction {

	private JdbcTemplate jdbcTemplate;
	private DataSourceTransactionManager transactionManager;
	private DefaultTransactionDefinition transactionDefinition;
	private String insertSql = "insert into account (balance) values ('100')";

	public void save() {
		// 初始化jdbcTemplate
		DataSource dataSource = getDataSource();
		jdbcTemplate = new JdbcTemplate(dataSource);

		// 创建事务管理器
		transactionManager = new DataSourceTransactionManager();
		transactionManager.setDataSource(dataSource);

		// 定义事务属性
		transactionDefinition = new DefaultTransactionDefinition();
		transactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

		// 开启事务
		TransactionStatus transactionStatus = transactionManager.getTransaction(transactionDefinition);

		// 执行业务逻辑
		try {
			jdbcTemplate.execute(insertSql);
			int i = 1 / 0;
			jdbcTemplate.execute(insertSql);
			transactionManager.commit(transactionStatus);
		} catch (DataAccessException e) {
			e.printStackTrace();
		} catch (TransactionException e) {
			transactionManager.rollback(transactionStatus);
			e.printStackTrace();
		}

	}

	public DataSource getDataSource() {
		BasicDataSource dataSource = new BasicDataSource();
		dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql://192.168.1.100:3306/spring_aop?" +
				"useSSL=false&useUnicode=true&characterEncoding=UTF-8");
		dataSource.setUsername("root");
		dataSource.setPassword("root");
		return dataSource;
	}
}
